package com.hpf.lease.web.admin.service.impl;

import com.hpf.lease.common.config.CommonException;
import com.hpf.lease.common.config.MinioConfig;
import com.hpf.lease.common.result.ResultCodeEnum;
import com.hpf.lease.model.bean.GraphInfo;
import com.hpf.lease.web.admin.service.FileService;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.RemoveObjectArgs;
import io.minio.errors.*;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.UUID;

@Service
@Slf4j
public class FileServiceImpl implements FileService {
    @Resource
    MinioClient client;
    @Override
    public boolean upload(MultipartFile file) {
        try {
            InputStream is = file.getInputStream();
            if (is.available() == 0) throw new CommonException(ResultCodeEnum.FILE_ERROR);
            String contentType = file.getContentType();
            String fileName = file.getOriginalFilename();
            assert fileName != null;
            String suffix = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
            if (!MinioConfig.MEDIA_TYPES.contains(suffix))
                throw new CommonException(ResultCodeEnum.FILE_TYPE_ERROR);
            String objectName = MinioConfig.MODULE +
                    new DateTime().toString("/yyyy/MM/dd") +
                    UUID.randomUUID().toString().substring(0,6) + suffix;
            client.putObject(PutObjectArgs.builder()
                    .bucket(MinioConfig.BUCKET).stream(is,is.available(),-1)
                    .object(objectName).contentType(contentType)
                    .build());
        } catch (Exception e) {
            log.error("这是文件问题{}", (Object) e.getStackTrace());
        }
        return true;
    }

    @Override
    public boolean deleteImage(String url) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        int index = (MinioConfig.ENDPOINT + "/" + MinioConfig.BUCKET).length();
        String imag = url.substring(index);
        client.removeObject(RemoveObjectArgs.builder()
                .bucket(MinioConfig.BUCKET).object(imag).build());
        return true;
    }

    @Override
    public void deleteImageBatch(List<GraphInfo> graphList) {
        try {
            for (GraphInfo graphInfo : graphList) {
                deleteImage(graphInfo.getUrl());
            }
        } catch (Exception e) {
            log.error("这是文件问题{}", (Object) e.getStackTrace());
        }
    }
}
